// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using SnapObjects.Commons;

namespace SnapObjects.Data
{
    internal class ModelEntryLazyParser<TModel> : ModelEntryLazyParserBase<TModel>, IEnumerable<IModelEntry<TModel>>
    {
        private const string ROWS_STATUS = "row-status";
        private const string ROWS_COLUMNS = "columns";

        public ModelEntryLazyParser(
            INodeReader nodeReader,
            IModelMeta modelMeta,
            DataFormatSetting setting,
            IDictionary<string, MetaColumn> metaColumns,
            RowFormat rowFormat = RowFormat.Normal)
            : base(nodeReader, modelMeta, setting, metaColumns, rowFormat)
        {
          
        }

        public IEnumerator<IModelEntry<TModel>> GetEnumerator()
        {
            for (var index = 0; this.Read(); index++)
            {
                if (this.ReadRowToModelEntry(index, out var modelEntry))
                {
                    if (this.FilterRow(index) &&
                            (_modelMeta == null || (_modelMeta != null && _sccessed > 0)))
                    {
                        yield return modelEntry;
                    }
                }
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        private bool ReadRowToModelEntry(int rowNum, out IModelEntry<TModel> modelEntry)
        {
            _sccessed = 0;
            _importeds.Clear();

            var readOnly = false;

            var row = _nodeReader.ReadAsNode();

            if (rowNum < _setting.StartRow ||                           //ignore header if data have header
                    (_setting.EndRow > 0 && rowNum > _setting.EndRow))
            {
                readOnly = true;
            }

            modelEntry = _rowFormat == RowFormat.Simple ?
                                this.GetSimpleRow(row, readOnly) :
                                    this.GetStandardRow(row, readOnly);

            return !readOnly;
        }

        private IModelEntry<TModel> GetSimpleRow(INodeReader nodeReader, bool readOnly)
        {
            var entry = new ModelEntry<TModel>(ModelState.NewModified);
            IValueReader column = null;

            for (var columnNum = 0; nodeReader.Read(); columnNum++)
            {
                if (nodeReader.CurrentNodeType != DataNodeType.Value)
                {
                    var node = nodeReader.ReadAsNode();

                    if (!node.Read())
                    {
                        if (!this.FilterColumn(columnNum, node.Name))
                        {
                            continue;
                        }

                        if (!readOnly)
                        {
                            this.SetPropertyEntry(entry, columnNum, node.Name, null);
                        }

                        continue;
                    }

                    column = node.ValueReader;
                }
                else
                {
                    column = nodeReader.ValueReader;
                }

                if (!this.FilterColumn(columnNum, column.Name))
                {
                    continue;
                }

                if (!readOnly)
                {
                    this.SetPropertyEntry(entry, columnNum, column.Name, column.Value);
                }
            }

            return entry;
        }

        private IModelEntry<TModel> GetStandardRow(INodeReader nodeReader, bool readOnly)
        {
            var node = this.MoveNextValue(nodeReader, ROWS_STATUS);

            var state = (ModelState)node.ValueReader.ToInt32().Value; //nodeReader
            state = _rowFormat == RowFormat.Delete ? ModelState.Deleted : state;

            var entry = new ModelEntry<TModel>(state);

            this.MoveNext(nodeReader, ROWS_COLUMNS);
            this.StanderdRowRead(entry, nodeReader.ReadAsNode(), readOnly);

            nodeReader.Read();

            return entry;
        }

        private bool FilterRow(int rowNum)
        {
            return rowNum >= _setting.StartRow && (_setting.EndRow < 0 || rowNum <= _setting.EndRow)
                ? true : false;
        }

        private int GetPropertyOffset(int nodeIndex)
        {
            return _setting.StartProperty >= 0
               ? nodeIndex - _setting.StartProperty
               : nodeIndex;
        }

        private bool CheckDwColumn(int columnNum)
        {
            if (_modelMeta == null)
            {
                return true;
            }

            var length = _setting.DwStartColumn >= 0
                ? _modelMeta.PropertyCount - _setting.DwStartColumn
                : _modelMeta.PropertyCount;

            return length > this.GetPropertyOffset(columnNum);
        }

        private bool CanReadColumn(int index, int columnNum)
        {
            return columnNum >= _setting.StartProperty && this.CheckDwColumn(columnNum) &&
                (_setting.EndProperty < 0 || columnNum <= _setting.EndProperty);
        }
    }
}
